<template>
  <basic-container filter-class="mt-0 ">
    <template #filter>
      <cert-list-filter
        v-model="queryState"
        :loading="loading"
        :join-group-disabled="!rows.length"
        @clear-select-ids="handleClearIds"
        @search="handleSearch()"
        @refresh="handleRefresh()"
        @refresh-row="handleRefreshRow"
      ></cert-list-filter>
    </template>
    <section class="cert-page">
      <div class="table-content basic-table">
        <cert-table
          ref="certTableRef"
          :check-all="checkAll"
          :data="data"
          :loading="loading"
          :disabled="disabled"
          :pagination="pagination"
          @sort-change="handleSortChange"
          @refresh="onRefresh"
          @refresh-row="handleRefreshRow"
        />
        <!-- @load-more="handleLoadMore" -->
        <basic-pagination
          :pagination="pagination"
          :disabled="loading"
          @change="getTableList()"
        />
      </div>
    </section>
    <batch-floating-btn
      v-if="certTableRef?.selectedIds.length"
      :selected-ids="certTableRef.selectedIds"
      @batch-download="handleBatchDownload"
      @batch-delete="handleBatchDelete"
      @clear-select-ids="handleClearIds"
    />
    <!--
    <template #footer>
      <basic-pagination
        v-model:check="checkAll"
        :indeterminate="indeterminate"
        :pagination="pagination"
        :disabled="loading"
        :batch-button-disabled="!rows.length"
        @change="getTableList()"
      />
    </template>
    -->
  </basic-container>
</template>

<script setup lang="ts">
import type { CertModel } from '@/apis/model/cert'

import BatchFloatingBtn from './components/BatchFloatingBtn.vue'
import CertListFilter from './components/CertListFilter.vue'
import CertTable from './components/CertTable.vue'
import type { ICertFormState } from './type'
const certTableRef = ref<InstanceType<typeof CertTable>>()
const certState = computed(() => useAppStore().certFilterState)

const queryState = reactive<ICertFormState & SortCustomParams>({
  domain_keyword: '' || certState.value.domain_keyword,
  limit: 0,
  offset: 30,
  provider: '' || certState.value.provider,
  status: '' || certState.value.status,
  sort: 'id',
  order: 'desc'
})

const {
  data,
  loading,
  pagination,
  run: getTableList,
  disabled
} = useListRequest(getCertListApi, queryState)
const { setMessageBox } = useMessageBox()
watch(
  () => pagination.page,
  val => {
    if (val === 2) {
    }
  }
)
// const tableSelectIds = computed(() => useCertStore().selectIds)
// const handleLoadMore = async () => {
//   if (Date.now() - refreshTime.value < 500) {
//     return
//   }
//   pagination.page++
//   if (pagination.offset < pagination.total) {
//     await getTableList()
//     if (certTableRef.value?.selectedIds.length) {
//       useCertStore().setSelectIds(certTableRef.value?.selectedIds)
//     } else {
//       useCertStore().setSelectIds([])
//     }
//     if (tableSelectIds.value.length) {
//       await nextTick()
//       certTableRef.value?.setSelectIds(tableSelectIds.value)
//     }
//   }
// }
/**选中的 */
const rows = computed(() => certTableRef.value?.getRows() || [])

function toggleAll(val: boolean) {
  certTableRef.value?.toggleAll(val)
}

const refreshTime = ref(0)

const {
  // indeterminate,
  checkAll
} = useTableCheck(data, rows, toggleAll)

function handleSortChange({ sort, order }: SortCustomParams) {
  if (!order) {
    queryState.order = 'desc'
  } else {
    queryState.order = order
  }
  if (!sort) {
    queryState.sort = 'created_at'
  } else {
    queryState.sort = sort
  }
  pagination.page = 1
}
const handleRefresh = () => {
  pagination.page = 1
  pagination.offset = 0
  // data.value = []
  getTableList()
  refreshTime.value = Date.now()
}
function handleSearch() {
  pagination.page = 1
  pagination.offset = 0
  // data.value = []
  getTableList()
  refreshTime.value = Date.now()
}

function onRefresh(isDelete?: boolean) {
  isDelete && decPageByData(pagination, data)
  // data.value = []
  // pagination.page = 1
  // pagination.offset = 0
  getTableList()
  refreshTime.value = Date.now()
}
// 刷新当前行数据
function handleRefreshRow(row: CertModel) {
  data.value.forEach(item => {
    if (item.id !== row.id) return
    Object.assign(item, row)
  })
}
function handleBatchDownload(ids: string[]) {
  downloadCertApi({ id_list: ids }).then((res: any) => {
    useDownloadZipByBase64(res.content, res.name)
  })
}
function handleClearIds() {
  certTableRef?.value?.reset()
}
function handleBatchDelete(ids: string[]) {
  setMessageBox({
    isHtml: true,
    content: '<p>确定删除选中证书？</p>',
    title: '提示',
    async submit() {
      try {
        await deleteCertApi({ id_list: ids! })
        ToastUtils.success('删除成功')
        certTableRef.value?.reset()
        // data.value = []
        // pagination.page = 1
        // pagination.offset = 0
        getTableList()
        setMessageBox({ visible: false })
      } finally {
        setMessageBox({ loading: false })
      }
    }
  })
}
</script>

<style lang="scss">
.cert-page {
  @apply w-full h-full bg-white py-6 rounded-lg flex flex-col;
  .table-content {
    @apply h-full flex flex-col;
    .el-table__inner-wrapper {
      &::before {
        height: 0px !important;
      }
    }
  }
}
</style>
